package com.kinglone.back.common.controller;

import com.kinglone.back.file.model.BasFile;
import com.kinglone.back.file.service.FileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 通用模块控制器
 * 供多模块使用的弹窗部分   s
 *
 * @author
 * @Date 2017-05-09 23:02:21
 */
@Controller
@RequestMapping("/common")
public class CommonController {

    private Logger log = LoggerFactory.getLogger(this.getClass());
    private String PREFIX = "/common/html/";

    @Autowired
    private FileService fileService;


    private final static String IE9 = "MSIE 9.0";
    private final static String IE8 = "MSIE 8.0";
    private final static String IE7 = "MSIE 7.0";
    private final static String IE6 = "MSIE 6.0";

   /* @RequestMapping(value = "/getDictCombox")
    @ResponseBody
    public ResultMsg getDictCombox(@RequestParam String pcode, String isAll) {

        ResultMsg resultMsg = new ResultMsg();

        try {
            //List<Map<String,Object>> list = basEqptypeDictService.getEqpTypeDict(parentcod);
            //resultMsg.setData(list);
            Map<String, Object> map = new HashMap<>();
            map.put("pcode", pcode);
            LinkedList<Combobox> list = dictService.getDoctListByPcode(map);
            if ("1".equals(isAll)) {
                Combobox combox = new Combobox();
                combox.setLable("全部");
                combox.setValue("");
                list.addFirst(combox);
            }
            resultMsg.setSuccess(true);
            resultMsg.setData(list);
        } catch (Exception e) {
            resultMsg.setSuccess(false);
            resultMsg.setMessage("数据异常,请联系管理员");
            e.printStackTrace();
        } finally {
            return resultMsg;
        }
    }*/

    /**
     * 获得历史报告预览地址
     *
     * @param id
     * @param fileId
     * @return
     */
   /* @RequestMapping(value = "/viewReport")
    @ResponseBody
    public Object viewReport(@RequestParam String id, String fileId, String subName) {

        ResultMsg resultMsg = new ResultMsg();

        try {
            if (ToolUtil.isEmpty(id)) {
                throw new ApplicationException("参数不能为空");
            }
            //没有文件记录的重新创建文件
            if (ToolUtil.isEmpty(fileId) || "0".equals(fileId)) {
                //首先读取文件目录,然后去目录查找 report.xls文件//后面转换成pdf文件,存储文件表,返回文件id
                IspReport report = ispReportService.selectById(id);
                String ftpPath = ReportConfig.SERVER_PATH;
                String filePath = ftpPath + report.getDataPath();
                String filename = filePath + "/" + subName;
                //查找文件是否存在
                BasFile f = new BasFile(filename);
                if (f.exists()) {
                    String uuid = ToolUtil.getUUID32();
                    String pdfname = filePath + "/" + uuid + ".pdf";
                    OpenOfficeUtil.docToPdf(filename, pdfname);
                    //新增文件表
                    BasUploadFile basUploadFile = new BasUploadFile();
                    basUploadFile.setId(uuid);
                    basUploadFile.setFromType("ispReportView");
                    basUploadFile.setFromId(id);
                    basUploadFile.setPath("img-pdf.png");//缩略图路径
                    basUploadFile.setFileName(uuid + ".pdf");
                    basUploadFile.setRealName(uuid + ".pdf");
                    basUploadFile.setRealFilePath(pdfname);
                    basUploadFile.setFileSuffix("pdf");
                    basUploadFile.setUpdateMan(ShiroKit.getUser().getAccount());
                    basUploadFile.setUpdateTime(DateUtil.getTime());
                    basUploadFile.setType("pdf");

                    basUploadFile.setPreviewPath(pdfname);
                    //插入文件记录
                    basUploadFileService.insert(basUploadFile);
                    resultMsg.setMessage("获取成功");
                    resultMsg.setData(basUploadFile.getId());
                } else {
                    throw new ApplicationException("报告书文件不存在无法预览");
                }
                //有文件记录的读取地址
            } else {
                resultMsg.setMessage("获取成功");
                resultMsg.setData(fileId);
            }

        } catch (ApplicationException e) {
            resultMsg.setSuccess(false);
            resultMsg.setMessage(e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            resultMsg.setSuccess(false);
            resultMsg.setMessage("数据异常,请联系管理员");
            e.printStackTrace();
        } finally {
            return resultMsg;
        }
    }*/

    /**
     * 跳转到表头调整弹窗
     * fromId 数据来源id
     * fromType 数据来源类型
     */
    @RequestMapping("/headWin/{tableId}")
    public String headWin(@PathVariable("tableId") String tableId, Model model) {

        model.addAttribute("tableId", tableId);
        return PREFIX + "head_win.html";
    }



    /**
     * 跳转到附件上传弹窗
     * fromId 数据来源id
     * fromType 数据来源类型
     */
    /*@RequestMapping("/uploadWin")
    public String uploadWin(HttpServletRequest request, String fromId, String fromType, Model model) {
        model.addAttribute("fromType", fromType);
        model.addAttribute("fromId", fromId);
        String broswer = checkBrowse(request);
        if("browser".equals(broswer)){
             return PREFIX + "upload_win.html";
            //return PREFIX + "upload_win_lowIE.html";
        }else{
            return PREFIX + "upload_win_lowIE.html";
        }
    }*/

    @RequestMapping("/icons")
    public String iconsPage(Model model) {

        return PREFIX + "icons.html";
    }

    /**
     * 上传图片
     */
    /*@RequestMapping(method = RequestMethod.POST, path = "/upload")
    @ResponseBody
    public void upload(HttpServletRequest request, String fromId, String fromType) {

        HashMap<String, Object> map = new HashMap<>();
        StringBuffer sb = new StringBuffer();
        //判断是否有文件
        MultipartHttpServletRequest request1 = (MultipartHttpServletRequest) request;
        MultiValueMap<String, MultipartFile> multiFileMap = request1.getMultiFileMap();
        Collection<List<MultipartFile>> values = multiFileMap.values();
        if (values.size() > 0) {
            for (List<MultipartFile> files : values) {
                for (MultipartFile file : files) {
                    //服务器上的文件名
                    String uuid = ToolUtil.getUUID32();
                    String pictureName = uuid + "." + ToolUtil.getFileSuffix(file.getOriginalFilename());
                    String suffix = ToolUtil.getFileSuffix(file.getOriginalFilename());
                    //根据后缀判断是什么文件,图片型的要缩略图,office 要特殊预览;其他类型缩略图固定化不提供预览
                    String flag = ToolUtil.getFileType(suffix);
                    String des = "";
                    String previewPath = "";
                    String type = "";
                    try {
                        String fileSavePath = gunsProperties.getFileUploadPath(fromType);
                        String path = fileSavePath + pictureName;
                        //图片的操作
                        if ("pic".equals(flag)) {
                            //图片同时生成一个缩略图
                            des = fileSavePath + "thum_" + pictureName;//缩略图实际存储路径
                            Thumbnails.of(file.getInputStream()).size(160, 160).toFile(des);//缩略图大小
                            type = flag;
                            //office的操作,需要生成一个同名的预览文件@_@
                        } else if ("word".equals(flag)) {
                            des = "img-word.png";
                        } else if ("exl".equals(flag)) {
                            des = "img-exl.png";
                        } else if ("pdf".equals(flag)) {
                            des = "img-pdf.png";
                            //其它文件的操作
                        } else if ("other".equals(flag)) {
                            des = "img-other.png";
                        }
                        type = flag;
                        //先 生成文件,用以后面使用
                        file.transferTo(new BasFile(path));
                        //然后office类文件可以生成pdf文件,生成同目录下的pdf文件路径
                        if ("word".equals(flag) || "exl".equals(flag)) {
                            previewPath = fileSavePath + uuid + ".pdf";
                            OpenOfficeUtil.docToPdf(path, previewPath);
                        } else if ("pdf".equals(flag)) {
                            previewPath = path;
                        }
                        //保存后数据插入数据库
                        BasUploadFile basUploadFile = new BasUploadFile();
                        basUploadFile.setFromType(fromType);
                        basUploadFile.setFromId(fromId);
                        basUploadFile.setPath(des);//缩略图路径
                        basUploadFile.setFileName(file.getOriginalFilename());
                        basUploadFile.setRealName(pictureName);
                        basUploadFile.setRealFilePath(path);
                        basUploadFile.setFileSuffix(suffix);
                        basUploadFile.setUpdateMan(ShiroKit.getUser().getAccount());
                        basUploadFile.setUpdateTime(DateUtil.getTime());
                        basUploadFile.setType(type);
                        basUploadFile.setPreviewPath(previewPath);
                        //插入文件记录
                        basUploadFileService.insert(basUploadFile);
                    } catch (Exception e) {
                        log.error(e.getMessage());
                        throw new GunsException(BizExceptionEnum.UPLOAD_ERROR);
                    }
                }
            }
        }
    }*/
    /**
     * 低版本ie上传文件
     */
    /*@RequestMapping(method = RequestMethod.POST, path = "/uploadLowIE",produces="text/html;charset=utf-8")
    public void uploadLowIE(HttpServletRequest request, HttpServletResponse response, String fromId, String fromType) {

        ResultMsg resultMsg = new ResultMsg();

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> multipartFiles = multipartRequest.getFiles("uploadFile");
        if(multipartFiles!=null && !multipartFiles.isEmpty()){
            MultipartFile file = multipartFiles.get(0);
            //服务器上的文件名
            String uuid = ToolUtil.getUUID32();
            String pictureName = uuid + "." + ToolUtil.getFileSuffix(file.getOriginalFilename());
            String suffix = ToolUtil.getFileSuffix(file.getOriginalFilename());
            //根据后缀判断是什么文件,图片型的要缩略图,office 要特殊预览;其他类型缩略图固定化不提供预览
            String flag = ToolUtil.getFileType(suffix);
            String des = "";
            String previewPath = "";
            String type = "";
            try {
                String fileSavePath = gunsProperties.getFileUploadPath(fromType);
                String path = fileSavePath + pictureName;
                //图片的操作
                if ("pic".equals(flag)) {
                    //图片同时生成一个缩略图
                    des = fileSavePath + "thum_" + pictureName;//缩略图实际存储路径
                    Thumbnails.of(file.getInputStream()).size(160, 160).toFile(des);//缩略图大小
                    type = flag;
                    //office的操作,需要生成一个同名的预览文件@_@
                } else if ("word".equals(flag)) {
                    des = "img-word.png";
                } else if ("exl".equals(flag)) {
                    des = "img-exl.png";
                } else if ("pdf".equals(flag)) {
                    des = "img-pdf.png";
                    //其它文件的操作
                } else if ("other".equals(flag)) {
                    des = "img-other.png";
                }
                type = flag;
                //先 生成文件,用以后面使用
                file.transferTo(new BasFile(path));
                //然后office类文件可以生成pdf文件,生成同目录下的pdf文件路径
                if ("word".equals(flag) || "exl".equals(flag)) {
                    previewPath = fileSavePath + uuid + ".pdf";
                    OpenOfficeUtil.docToPdf(path, previewPath);
                } else if ("pdf".equals(flag)) {
                    previewPath = path;
                }
                //保存后数据插入数据库
                BasUploadFile basUploadFile = new BasUploadFile();
                basUploadFile.setFromType(fromType);
                basUploadFile.setFromId(fromId);
                basUploadFile.setPath(des);//缩略图路径
                basUploadFile.setFileName(file.getOriginalFilename());
                basUploadFile.setRealName(pictureName);
                basUploadFile.setRealFilePath(path);
                basUploadFile.setFileSuffix(suffix);
                basUploadFile.setUpdateMan(ShiroKit.getUser().getAccount());
                basUploadFile.setUpdateTime(DateUtil.getTime());
                basUploadFile.setType(type);
                basUploadFile.setPreviewPath(previewPath);
                //插入文件记录
                basUploadFileService.insert(basUploadFile);
            } catch (Exception e) {
                log.error(e.getMessage());
                throw new GunsException(BizExceptionEnum.UPLOAD_ERROR);
            }
        }
        resultMsg.setSuccess(true);
        try {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            //out.write("{ success:'" + false + "', msg:'" + 1212 + "',imgurl:'" + 121 + "'}");
            out.write(JSON.toJSONString(resultMsg));
            out.close();
        }catch (IOException e){
            throw new GunsException(BizExceptionEnum.UPLOAD_ERROR);
        }
    }
*/
    /**
     * 返回缩略图图片
     *
     * @author mty
     * @Date 2018.9.18
     */
    /*@RequestMapping("/thumPic/{fileId}")
    public void thumPic(@PathVariable("fileId") String fileId, HttpServletResponse response, HttpServletRequest request) {
        //根据id获取缩略图地址
        BasUploadFile file = basUploadFileService.selectById(fileId);
        String path = file.getPath();
        try {
            if (path.startsWith("img")) {
                //获取项目中图片
                String imgPath = request.getContextPath() + "/static/img/" + path.replace("img-", "");
                response.sendRedirect(imgPath);
            } else {
                byte[] bytes = FileUtil.toByteArray(path);
                response.getOutputStream().write(bytes);
            }
        } catch (Exception e) {
            //如果找不到图片就返回一个默认图片
            try {
                response.sendRedirect(request.getContextPath() + "/static/img/girl.gif");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }*/

    /**
     * 获得图片列表
     */
   /* @RequestMapping(method = RequestMethod.POST, path = "/getFileListById")
    @ResponseBody
    public ResultMsg getFileListById(String fromId, String fromType) {
        ResultMsg msg = new ResultMsg();
        //获取通知对应的附件列表
        List<BasUploadFile> files = basUploadFileService.getFileListForId(fromId, fromType);
        msg.setData(files);
        return msg;
    }*/

    /**
     * 删除图片
     */
    /*@RequestMapping("/file/delete/{id}")
    @ResponseBody
    public ResultMsg delFile(@PathVariable("id") String id) {
        ResultMsg msg = new ResultMsg();
        //获取通知对应的附件列表
        BasUploadFile file = new BasUploadFile();
        file.setId(id);
        file.setIsDel(1);
        file.setUpdateMan(ShiroKit.getUser().getAccount());
        file.setUpdateTime(DateUtil.getTime());
        file.updateById();
        msg.setMessage("删除成功!");
        return msg;
    }*/

    /**
     * 下载文件
     */
   /* @RequestMapping("/file/down/{id}")
    @ResponseBody
    public void downFile(@PathVariable("id") String id, HttpServletResponse res, HttpServletResponse response) {

        BasUploadFile uploadfile = basUploadFileService.selectById(id);
        BasFile file = new BasFile(uploadfile.getRealFilePath());
        if (file.exists()) {

            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition",
                        "attachment;fileName=" + new String(uploadfile.getFileName().getBytes("GB2312"), "iso8859-1"));// 设置文件名
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            log.debug("下载成功");
        } else {
            log.debug("文件不存在");
        }

    }*/

    /**
     * 预览pdf
     */
    @RequestMapping("/file/view/{id}")
    @ResponseBody
    public void viewFile(@PathVariable("id") String id, HttpServletResponse res, HttpServletResponse response) {

        BasFile uploadfile = fileService.selectById(id);
        File file = new File(uploadfile.getReal_file_path());
        if (file.exists()) {

            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                response.setContentType("application/pdf;charset=UTF-8");


                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            log.debug("预览成功");
        } else {
            log.debug("文件不存在");
        }

    }

    /**
     * 预览图片
     */
   /* @RequestMapping("/file/viewPic/{id}")
    @ResponseBody
    public void viewPic(@PathVariable("id") String id, HttpServletResponse res, HttpServletResponse response) {

        BasUploadFile uploadfile = basUploadFileService.selectById(id);
        BasFile file = new BasFile(uploadfile.getRealFilePath());
        if (file.exists()) {

            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                response.setContentType("text/html; charset=UTF-8");
                response.setContentType("image/jpeg");
            *//*    response.addHeader("Content-Disposition",
                        "attachment;fileName=" +  new String(uploadfile.getFileName().getBytes("GB2312"),"iso8859-1" ));// 设置文件名*//*
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            log.debug("下载成功");
        } else {
            log.debug("文件不存在");
        }

    }*/



    /**
     * 判断浏览器，只针对ie9,8,7,6 其他浏览器统一命名为browser
     * @param request
     * @return
     */
    public static String checkBrowse(HttpServletRequest request) {
        String userAgent=request.getHeader("USER-AGENT");
        if (regex(IE9, userAgent)){
            return IE9;
        }else if (regex(IE8, userAgent)){
            return IE8;
        }else if (regex(IE7, userAgent)){
            return IE7;
        }else if (regex(IE6, userAgent)){
            return IE6;
        }else{
            return "browser";
        }
    }
    public static boolean regex(String regex, String str) {
        Pattern p = Pattern.compile(regex, Pattern.MULTILINE);
        Matcher m = p.matcher(str);
        return m.find();
    }
}
